package tech.dongliang.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.dongliang.system.dao.SysUserDao;
import tech.dongliang.system.dao.SysUserRoleDao;
import tech.dongliang.system.model.SysUser;
import tech.dongliang.system.service.ISysUserService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xdzhang
 * @since 2019-01-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements ISysUserService {
    @Autowired
    private SysUserRoleDao userRoleDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SysUser entity) {
        if (super.save(entity)) {
            try {
                userRoleDao.removeByUserId(entity.getId());
                userRoleDao.insertRole(entity.getId(), entity.getRoleIds());
            } catch (Exception e) {
                return false;
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(SysUser entity) {
        try {
            userRoleDao.removeByUserId(entity.getId());
            userRoleDao.insertRole(entity.getId(), entity.getRoleIds());
            return super.updateById(entity);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean changeStatus(Integer userId, Integer status) throws Exception {
        SysUser user = baseMapper.selectById(userId);
        user.setStatus(status);
        return baseMapper.updateById(user) > 0;
    }

    @Override
    public SysUser getByUsername(String username) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.eq("username", username);
        return baseMapper.selectOne(query);
    }
}
